/**
* @Author: qinhaoda
* @Description:
* @File: router_env
* @Version: 1.0.0
* @Date: 2022/12/28 17:46
 */
package http

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/didi/nightingale/src/common/address"
	"github.com/didi/nightingale/src/models"
	"github.com/gin-gonic/gin"
	"github.com/toolkits/pkg/errors"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
)

func getMd5DiffFile(c *gin.Context) {
	endpoint := urlParamStr(c, "endpoint")
	id := urlParamStr(c, "id")
	addr := address.GetHTTPListen("agent")
	port := strings.Split(addr, ":")[1]
	url := fmt.Sprintf("http://%s:%s/output/%s/md5diff/file", endpoint, port, id)
	client := &http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}
	resp, err := client.Get(url)
	errors.Dangerous(err)

	defer resp.Body.Close()

	bs, err := ioutil.ReadAll(resp.Body)
	errors.Dangerous(err)

	c.Writer.Header().Set("Content-Type", "application/json; charset=UTF-8")
	c.Writer.Write(bs)
}

func getMd5DiffContent(c *gin.Context) {
	endpoint := urlParamStr(c, "endpoint")
	id := urlParamStr(c, "id")
	addr := address.GetHTTPListen("agent")
	port := strings.Split(addr, ":")[1]
	url := fmt.Sprintf("http://%s:%s/output/%s/md5diff/content", endpoint, port, id)
	client := &http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}
	resp, err := client.Get(url)
	errors.Dangerous(err)

	defer resp.Body.Close()

	bs, err := ioutil.ReadAll(resp.Body)
	errors.Dangerous(err)

	c.Writer.Header().Set("Content-Type", "application/json; charset=UTF-8")
	c.Writer.Write(bs)
}

func serviceRun(c *gin.Context) {
	var recv struct {
		ID    int64    `json:"id"`
		Hosts []string `json:"hosts"`
	}
	errors.Dangerous(c.ShouldBindJSON(&recv))
	addr := address.GetHTTPListen("agent")
	port := strings.Split(addr, ":")[1]
	check, err := models.GetServiceCollectByID(recv.ID)
	if err != nil || check == nil {
		errors.Dangerous(err)
	}
	checkData, err := json.Marshal(check)
	if err != nil {
		errors.Dangerous(err)
	}
	for _, host := range recv.Hosts {
		url := fmt.Sprintf("http://%s:%s/api/collector/service/run", host, port)
		client := &http.Client{
			CheckRedirect: func(req *http.Request, via []*http.Request) error {
				return http.ErrUseLastResponse
			},
		}
		resp, err := client.Post(url, "application/json", bytes.NewBuffer(checkData))
		errors.Dangerous(err)

		defer resp.Body.Close()
		if resp.StatusCode != 200 {
			errors.Dangerous(fmt.Errorf("%v status code is not 200", url))
		}
		body, err := io.ReadAll(resp.Body)
		errors.Dangerous(err)

		var dat struct {
			Dat string `json:"dat"`
			Err string `json:"err"`
		}
		err = json.Unmarshal(body, &dat)
		if err != nil {
			errors.Dangerous(err)
		}
		if dat.Dat != "ok" {
			errors.Dangerous(err)
		}
	}
	renderData(c, "ok", nil)
}

func checkRun(c *gin.Context) {
	var recv struct {
		ID    int64    `json:"id"`
		Hosts []string `json:"hosts"`
	}
	errors.Dangerous(c.ShouldBindJSON(&recv))
	addr := address.GetHTTPListen("agent")
	port := strings.Split(addr, ":")[1]
	check, err := models.GetCheckCollectByID(recv.ID)
	if err != nil || check == nil {
		errors.Dangerous(err)
	}
	checkData, err := json.Marshal(check)
	if err != nil {
		errors.Dangerous(err)
	}
	for _, host := range recv.Hosts {
		url := fmt.Sprintf("http://%s:%s/api/collector/check/run", host, port)
		client := &http.Client{
			CheckRedirect: func(req *http.Request, via []*http.Request) error {
				return http.ErrUseLastResponse
			},
		}
		resp, err := client.Post(url, "application/json", bytes.NewBuffer(checkData))
		if err != nil {
			errors.Dangerous(err)
		}
		defer resp.Body.Close()
		if resp.StatusCode != 200 {
			errors.Dangerous(fmt.Errorf("%v status code is not 200", url))
		}
		body, err := io.ReadAll(resp.Body)
		if err != nil {
			errors.Dangerous(err)
		}
		var dat struct {
			Dat string `json:"dat"`
			Err string `json:"err"`
		}
		err = json.Unmarshal(body, &dat)
		if err != nil {
			errors.Dangerous(err)
		}
		if dat.Dat != "ok" {
			errors.Dangerous(err)
		}
	}
	renderData(c, "ok", nil)
}
